import downFtp
import upFile
import os
import configparser
import time
import datetime
import sys
import shutil

import fnmatch

def upFiles():
    file = "./saveZip/"
    # ftpList = cf.options("ftp_source")
    server_ip = cf.get("ftp_up", "up_server")
    server_user = cf.get("ftp_up", "up_server_user")
    server_pwd = cf.get("ftp_up", "up_server_pwd")
    saveas_file_path= cf.get("ftp_up", "saveas_file_path")

    # my_ftp = upFile.UpFTP(server_ip)
    # my_ftp.login(server_user, server_pwd)
    # 上传目录
    typeList = filename.split("_")
    # target = "source/" + typeList[1] + "/" + typeList[0] + "/" + filename
    # target = "source/" + filename  原始的

    fileSize = os.path.getsize(file + filename)
    if fileSize < 50:
        os.remove(file + filename)
        # my_ftp.close()
        return
    # my_ftp.upload_file(file + filename, target)

    # os.remove(file + filename)
    # my_ftp.close()
    #  20240818 ---      改为存储到解析文件所在文件夹下的source
    src_file_path = file + filename
    dst_file_path = saveas_file_path + typeList[1] + "/" + typeList[0] + "/" + filename
    shutil.copy(src_file_path, dst_file_path)
    os.remove(file + filename)

def downForOne(indexHead):
    ftpList = cf.options("ftp_source")
    key = ftpList[indexHead]

    cfgStr = cf.get("ftp_source", key)
    attributes = cfgStr.split(',')
    ftp = downFtp.DownFtp(attributes[0], key)
    keyAttributes = key.split("_")


    global todayStr
    global filename
    filename = key + "_" + todayStr + ".zip"
    ftp.creatZip(filename)
    isCon = ftp.login(attributes[2], attributes[3])
    if not isCon:
        return False
    ### for test begin
    """
    if attributes[4] in ("*", ""):
        print(key + ",pass")
    else:
        file  = "FFFF_custom_packed_20250128.tar.gz"
        fileNameList = file.split(".")
        if fnmatch.fnmatch(file, attributes[4]):
            print(attributes[4] + ",match!")
            print("file_date: " + fileNameList[0][-8:])
        else:
            print(attributes[4] + ",no match!")
    """
    ### for test end

    if keyAttributes[1] == "1" or keyAttributes[1] == "4" or keyAttributes[1] == "5" or keyAttributes[1] == "16":
        # 当天
        ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + (datetime.datetime.strptime(todayStr, "%Y%m%d"))
                             .strftime("%d") + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr, key, attributes[4])

        # 前一天
        lastDate = (datetime.datetime.strptime(todayStr, "%Y%m%d") + datetime.timedelta(days=-1)).strftime("%d")
        isSucsse = ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + lastDate + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr,
                                        key, attributes[4])
        ftp.close()

        return isSucsse

    if keyAttributes[1] == "3":
        # 当天

        ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + todayStr + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr, key, attributes[4])

        # 前一天
        lastDate = (datetime.datetime.strptime(todayStr, "%Y%m%d") + datetime.timedelta(days=-1)).strftime("%Y%m%d")
        isSucsse = ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + lastDate + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr,
                                        key, attributes[4])

        ftp.close()

        return isSucsse
    if keyAttributes[1] == "2" or keyAttributes[1] == "14" or keyAttributes[1] == "36":
        # 20250223 add begin
        lastDate = (datetime.datetime.strptime(todayStr, "%Y%m%d") + datetime.timedelta(days=-1)).strftime("%Y%m%d")
        # end
        isSucsse = ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + lastDate + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr, key, attributes[4])

        ftp.close()
        return isSucsse

    if keyAttributes[1] == "6" or keyAttributes[1] == "9":
        if keyAttributes[0] == "acc":
            # 当天
            lastDate = todayStr
        else:
            # 前一天
            lastDate = (datetime.datetime.strptime(todayStr, "%Y%m%d") + datetime.timedelta(days=-1)).strftime("%Y%m%d")

        # test begin
        #print((attributes[1][:-1] + lastDate + "/") if attributes[1][-1:] == "?" else attributes[1])
        #return True
        # test end

        isSucsse = ftp.DownLoadFileTree("./saveZip/", (attributes[1][:-1] + lastDate + "/") if attributes[1][-1:] == "?" else attributes[1], lastTime, currenTime, todayStr,key, attributes[4])
        ftp.close()
        return isSucsse

    return True


if __name__ == "__main__":

    cf = configparser.ConfigParser()
    cf.read("./conf/deal.conf")

    filename = ""
    todayStr = time.strftime("%Y%m%d", time.localtime(time.time()))
    lastTime = "0200"
    currenTime = "0200"

    begin = int(sys.argv[1])
    length = int(sys.argv[2])
    #if int(sys.argv[3]) is not 0:
    if int(sys.argv[3]) != 0:
        todayStr = sys.argv[3]

    lastTime = sys.argv[4]
    currenTime = sys.argv[5]

    """test begin
    file = "FFFF_custom_packed_20250128.tar.gz"
    fileNameList = file.split(".")
    fileDate = fileNameList[0][-8:]
    if len(fileDate) == 8:
        fileDate = fileDate + lastTime
    if len(fileDate) < 14:
        # fileDate = fileDate + "00"
        # 20250225 改成填充14位方式
        fileDate = fileDate.ljust(14, '0')
    print("filedate:{}".format(fileDate))
    exit(1)
    """

    start_time = time.time()
    print(str(begin) + "-" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    #shutil.copy("/data/ftpGet/saveZip/sc_14_1_1_20240903.zip", "/data/ftpAndAlnysis/source/14/sc")

    for index in range(begin, begin + length):
        isOk = downForOne(index)
        # if not isOk:
        #    file = "./saveZip/"
        #    os.remove(file + filename)
        #   continue
        upFiles()
    print(str(begin) + "-" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print(str(begin), 'all time : ', time.time() - start_time)
